package com.letv.so.util;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import com.alibaba.fastjson.JSON;
import com.letv.so.bean.AlbumBean;
import com.letv.so.bean.VideoBean;
import com.letv.so.constants.Constants;
import com.letv.so.constants.DownPlatFormEnum;
import com.letv.so.constants.PayPlatFormEnum;

import serving.AlbumAttribute;
import serving.CinemaInfo;
import serving.DataType;
import serving.IdAndName;
import serving.ResultDocInfo;
import serving.VideoAttributeInAlbum;

public class BisUtil {
    public static List<String> subList(int fromIndex, int toIndex,
            List<String> infoLists) {
        int size1 = infoLists.size();
        if (toIndex<=size1) {
            return infoLists.subList(fromIndex, toIndex);
        }else {
            if (fromIndex<size1) {
                return infoLists.subList(fromIndex, size1);
            }
        }
        return new ArrayList<String>();
    }

    public static List<String> getList(String info) {
        String[] infos =  StringUtil.isNotBlank(info) ? info.split(";") : new String[0];
        return Arrays.asList(infos);
    }

    public static void convertStr2List(String strs, ArrayList<String> list) {
        if (StringUtils.isNotBlank(strs)) {
            String[] strsArray = strs.split(";");
            if (null!=strsArray) {
                for (String str : strsArray) {
                    if (StringUtils.isNotBlank(str)) {
                        String[] dd = str.split("\\|");
                        if (dd.length==2) {
                            list.add(dd[1]);
                        }
                    }
                }
            }
        }
    }
    
    public static String getOrderlist(List<String> orders) {
        StringBuffer sb = new StringBuffer();
        int size = orders.size();
        for (int i = 0; i < size; i++) {
            sb.append(orders.get(i));
            if (i != size) {
                sb.append(";");
            }
        }
        return sb.toString();
    }

    public static String getTaglist(List<String> vidLists, int ps,List<String> orders) {
        StringBuffer tags = new StringBuffer();
        int count = 0;
        if (vidLists.size() != 0) {
            count = vidLists.size() / ps;
            if (vidLists.size() % ps != 0) {
                count ++;
            }

            tags.append("all:1-").append(count).append(":");
        }
        boolean beginZero = (orders.size() >0 && orders.get(0).equals("0"));
        int index = beginZero?(vidLists.size()-1):vidLists.size();
        int one = beginZero?1:0;
        int zero = beginZero?0:1;
        for (int i = 0; i < count; i++) {
            int start = zero + i * ps;
            int end =  ((i + 1) * ps)-one;
            if (index>=end) {
                tags.append(start).append("-").append(end);
            } else {
                if (index==start) {
                    tags.append(start);
                } else {
                    tags.append(start).append("-").append(index);
                }
             }
             if (i!=count) {
               tags.append(";");
             }
        }

        return tags.toString();
    }

    public static String MD5(String s) {
        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public static void setPayAndDownFlag(VideoBean videoBean) {
        String ph = ThreadLocalUtil.getPh();
        if (StringUtils.isNotBlank(ph)) {
            String payPlatform = videoBean.getPayPlatform();
            String isPay = "0";
            String allowdown = "0";
            if (StringUtils.isNotBlank(payPlatform)) {
                isPay = calcIsPay(payPlatform,ph);
            }
            if ( StringUtils.isNotEmpty(isPay)) {
                videoBean.setIsPay(isPay);
            }
/*            String downloadPlatform = videoBean.getDownloadPlatform();
            if (StringUtils.isNotBlank(downloadPlatform)) {
                allowdown = calcDownload(downloadPlatform,ph);
            }
            if ( StringUtils.isNotEmpty(allowdown)) {
                videoBean.setAllowDownload(allowdown);
            }
            videoBean.setDownloadPlatform(null);*/
        }
        videoBean.setPayPlatform(null);
    }
    
    public static String calcDownload(String downloadPlatform,String ph) {
         DownPlatFormEnum downEnum = DownPlatFormEnum.valueOf(ph);
         if (downEnum != null) {
              if (downloadPlatform.indexOf(downEnum.getValue()) > 0) {
                  return "1";
              }else {
                  return "0";
              }
         }
        return null;
    }

    public static String calcIsPay(String payPlatform,String ph) {
            PayPlatFormEnum payEnum = PayPlatFormEnum.valueOf(ph);
            if (payEnum != null) {
                if (payPlatform.indexOf(payEnum.getValue()) > 0) {
                    return "1";
                } else {
                    return "0";
                }
            }
        return null;
    }

    public static ResultDocInfo album2thrift(AlbumBean album) {
        ResultDocInfo info = new ResultDocInfo();
        AlbumAttribute albumAtt = new AlbumAttribute();
        info.setCategory(album.getCategory());
        info.setCategory_name(album.getCategoryName());
        info.setId(album.getAid());
        info.setName(album.getName());
        info.setGlobal_id("");
        info.setAlbum_attribute(albumAtt);
        albumAtt.setAid(album.getAid());
        albumAtt.setArea_name(album.getAreaName());
        String subSrc = album.getSubSrc();
        albumAtt.setSub_src(subSrc);
        albumAtt.setSrc(StringUtils.isBlank(album.getSrc())?0:Short.valueOf(album.getSrc()));
        albumAtt.setSub_name(album.getSubName());
        albumAtt.setName(album.getName());
        albumAtt.setRating(album.getRating());
        albumAtt.setSub_category_name(album.getSubCategoryName());
        albumAtt.setDownload_platform(getIdList(album.getDownloadPlatform(),","));
        albumAtt.setPush_flag(getIdList(album.getPushFlag(),","));
        albumAtt.setPay_platform(getIdList(removeSplit(album.getAlbum_pay_platform(), ","),","));
        albumAtt.setIs_end(StringUtils.isBlank(album.getIsEnd())?0:Short.valueOf(album.getIsEnd()));
        albumAtt.setArea_name(album.getAreaName());
        albumAtt.setRelease_date(DateUtil.getTime(album.getReleaseDate()));
        String director = album.getDirectory();
        String actor = album.getStarring();
/*        if (Constants.WEBSITE_LETV.equals(album.getSubSrc())) {
            director = getNormalStr(director,",",";");
            actor = getNormalStr(actor,",",";");
        }*/
        albumAtt.setDirector(getNameList(director,";"));
        albumAtt.setStarring(getNameList(actor,";"));
        Map<String,String> images = new HashMap<String,String>();
        images.put("postS1", album.getPostS1());
        images.put("postS2", album.getPostS2());
        images.put("cmsImages", JSON.toJSONString(album.getCmsImages()));
        albumAtt.setImages(images);
        albumAtt.setIs_pay(StringUtils.isBlank(album.getIspay())?0:Short.valueOf(album.getIspay()));
        albumAtt.setEpisodes(StringUtils.isBlank(album.getEpisodes())?0:Short.valueOf(album.getEpisodes()));
        albumAtt.setNow_episode(album.getNowEpisodes());
        albumAtt.setPlay_streams(album.getPlayStreams());
        albumAtt.setVideo_type(StringUtils.isBlank(album.getVideoType())?180001:Integer.valueOf(album.getVideoType()));
        albumAtt.setVideo_type_name(album.getVideoTypeName());
        albumAtt.setFit_age(album.getFitAge());
        albumAtt.setLanguage(album.getLanguage());
        albumAtt.setAlbum_pic(album.getAlbumPic());
        albumAtt.setTag(album.getTag());
        albumAtt.setPlay_count(StringUtils.isBlank(album.getPlayCount())?90000:Long.valueOf(album.getPlayCount()));
        albumAtt.setShort_desc(album.getShortDesc());
        albumAtt.setMonth_count(album.getMonthCount());
        albumAtt.setDuration(album.getDuration());
        albumAtt.setName_jianpin(album.getNameJianpin());
        albumAtt.setName_quanpin(album.getNameQuanpin());
        albumAtt.setDay_count(album.getDayCount());
        if (StringUtils.isNotEmpty(album.getPrice())) {
            CinemaInfo cinemaInfo = new CinemaInfo();
            cinemaInfo.setPrice(album.getPrice());
            cinemaInfo.setVprice(album.getVprice());
            cinemaInfo.setStart_time(album.getStarttime());
            cinemaInfo.setEnd_time(album.getEndtime());
            albumAtt.setCinema_info(cinemaInfo);
        }
        //albumAtt.setComment_count();
        albumAtt.setVideo_list(convertVideo(album.getVideoList()));
        return info;
    }

    /**
     * remove the first and last separate if need
     * @param str String
     * @param separate String
     * @return String
     */
    private static String removeSplit(String str, String separate) {
        if(StringUtils.isBlank(str) || StringUtils.isBlank(separate)) {
            return null;
        }
        try {
            if(str.startsWith(separate)) {
                str = str.substring(1);
            }
        } catch(Exception e) {
        }
        return str;
    }

    private static List<VideoAttributeInAlbum> convertVideo(
            List<VideoBean> videoList) {
        if (videoList!=null && videoList.size() >0) {
            List<VideoAttributeInAlbum> vlt = new ArrayList<VideoAttributeInAlbum>();
            for (VideoBean vb:videoList) {
                VideoAttributeInAlbum av = new VideoAttributeInAlbum();
                av.setData_type(DataType.VIDEO);
                av.setAlbum_letv_original_id(Constants.LESO_ALBUM_PERFIX + vb.getAid());
                av.setCategory(vb.getCategory());
                av.setUnique_id(vb.getUnid());
                av.setEpisode(vb.getAorder());
                av.setName(vb.getName());
                av.setSub_name(vb.getSubName());
                av.setMid(vb.getMid());
                av.setUrl(vb.getUrl());
                av.setLetv_original_id(vb.getLetvOrininalSvid());
                av.setVideo_type(vb.getVideoType());
                av.setIs_pay(StringUtils.isBlank(vb.getIsPay())?null:Short.valueOf(vb.getIsPay()));
                String paypf = vb.getPayPlatform();
                paypf = getNormalStr(paypf,",",",");
                av.setPay_platform(getIdList(paypf,","));
                av.setPlay_streams(vb.getPlayStreams());
                av.setId(vb.getVid());
                av.setArea_allow(true); //需要判断
                if (StringUtils.isNotBlank(vb.getVideoPanid())) {
                	av.setExternal_id(vb.getVideoPanid());
                }else {
                    av.setExternal_id(vb.getExternal_id());
                }
                av.setDuration(vb.getDuration());
                String aorder = vb.getAorder();
                int order = StringUtils.isBlank(aorder)?0:(NumberUtils.isDigits(aorder)?Integer.valueOf(vb.getAorder()):0);
                av.setPorder(order);
                String downpf = vb.getDownloadPlatform();
                downpf = getNormalStr(downpf,",",",");
                av.setDownload_platform(getIdList(downpf,","));
                Map<String,String> map = new HashMap<String,String>();
                map.put("images", vb.getImages() == null?"":vb.getImages());
                av.setImages(map);
                vlt.add(av);
            }
            return vlt;
        }
        return null;
    }

    private static List<IdAndName> getIdList(String keys,String splitor){
    	List<IdAndName> idNames = new ArrayList<IdAndName>();
        if (StringUtils.isNotBlank(keys)) {
            String[] keyarr = keys.split(splitor);
            for (String key :keyarr) {
                  IdAndName kv = new IdAndName();
                  kv.setId(key);
                  kv.setName("");
                  idNames.add(kv);
            }
        }
        return idNames;
    }
    

    private static List<IdAndName> getNameList(String values, String splitor) {
        List<IdAndName> appendList = new ArrayList<IdAndName>();
        String[] valuearr = values.split(splitor);
        for (int i=0 ;i <valuearr.length;i++ ) {
             IdAndName kv = new IdAndName();
             kv.setId("");
             kv.setName(valuearr[i]);
             appendList.add(kv);
        }
        return appendList;
	}

	private static String getNormalStr(String keys, String splitor,String nsp) {
        if (StringUtils.isBlank(keys)) {
            return keys;
        }
        String[] ids = keys.split(splitor);
        
        String para = "";
        for (String id: ids) {
            if (StringUtils.isNotBlank(id) && !id.equals(splitor)) {
                para +=id+nsp;
            }
        }
        if (para.endsWith(nsp)) {
            para = para.substring(0, para.length()-1);
        }
        return para;
    }
    
    public static void main(String[] args) {
        System.out.println(getIdList(removeSplit(",420007,402221", ","),","));
    }
        
}
